package arrray;

/**
 * @author huangxianjin
 * @date 2025/8/12 22:44
 * @description "买卖股票的最佳时机"
 */
public class LC_121 {

    //自己的做法-暴力法（双层for循环）
    public int maxProfit(int[] prices) {
        int maxProfit = 0;
        if (prices == null || prices.length < 1) {
            return 0;
        }
        for (int i = 0; i < prices.length - 1; i++) {
            int min = prices[i];
            for (int j = i + 1; j < prices.length; j++) {
                int max = prices[j];
                if (max - min > maxProfit) {
                    maxProfit = max - min;
                }
            }
        }
        return maxProfit;
    }

    //自己的做法2-双指针[本题不适合用双指针，因为无法确定左右指针下一步改如何移动]
//    public int maxProfit2(int[] prices) {
//        int maxProfit = 0;
//        if (prices == null || prices.length < 1) {
//            return 0;
//        }
//        int left = 0;
//        int right = prices.length - 1;
//        while (left < right) {
//            if (prices[right] - prices[left] > maxProfit) {
//                maxProfit = prices[right] - prices[left];
//                right--;
//            } else {
//                left++;
//            }
//        }
//        return maxProfit;
//    }

    //官方做法-一次遍历
    public int maxProfit3(int prices[]) {
        int minprice = Integer.MAX_VALUE;
        int maxprofit = 0;
        for (int i = 0; i < prices.length; i++) {
            if (prices[i] < minprice) {
                minprice = prices[i];
            } else if (prices[i] - minprice > maxprofit) {
                maxprofit = prices[i] - minprice;
            }
        }
        return maxprofit;
    }
}
